<template>
  <!--注册组件-->
  <div id="register">
    <Form ref="formCustom" :model="formCustom" :rules="ruleCustom" class="register-form" >
      <h3 class="title">Bingo系统</h3>
      <FormItem prop="nickName">
        <Input prefix="ios-contact" type="text" v-model="formCustom.nickName" placeholder="请输入用户名" ></Input>
      </FormItem>
      <FormItem prop="passwd">
        <Input prefix="md-grid" type="password" v-model="formCustom.passwd" placeholder="至少六位密码区分大小写" ></Input>
      </FormItem>
      <FormItem prop="passwdCheck">
        <Input prefix="md-grid" type="password" v-model="formCustom.passwdCheck" placeholder="确认密码" ></Input>
      </FormItem>
      <FormItem>
        <Input type="text" v-model="phone" placeholder="请输入电话号码" ></Input>
      </FormItem>
      <FormItem>
        <Input prefix="md-grid" type="text" v-model="verificationCode"
               placeholder="请输入验证码" style="width: 60%"
               @keyup.enter.native="handleSubmit('formCustom')"
              ></Input>
        <div class="register-code">
          <img :src="img_url" class="register-code-img" @click="getCaptcha">
        </div>
      </FormItem>
      <FormItem>
        <Button type="primary" @click="handleSubmit('formCustom')" style="width:100%;">立即注册</Button>
      </FormItem>
    </Form>
    <!--  底部  -->
    <div class="register-footer">
      <span>Bingo---一个集成视频与贴文的娱乐系统</span>
    </div>
  </div>
</template>

<script>
import base64 from "../utils/base64";
export default {
  name: "Register",
  data(){
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('密码不能为空'));
      }
      else if(value.length<6){
        callback(new Error('密码至少输入六位'));
      }
      callback();
    };
    const validatePassCheck = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('密码不能为空'));
      }
      else if(value !== this.formCustom.passwd){
        callback(new Error('两次密码不一致请重新输入'));
      }
      callback();
    };
    const validateNick = (rule,value,callback)=>{
      if (value === '') {
        callback(new Error('用户名不能为空'));
      }
      callback();
    };
    return{
      gender:0,   //1为男 2为女  0为未知
      img_url:'',
      phone:'',
      uuid:'',    //获取验证码后的唯一标识
      verificationCode:'',
      formCustom:{
        nickName:'',
        passwd:'',
        passwdCheck:''
      },
      ruleCustom: {
        nickName:[
          {validator:validateNick,trigger:'blur'}
        ],
        passwd: [
          {validator:validatePass,trigger: 'blur' }
        ],
        passwdCheck:[
          {validator:validatePassCheck,trigger:'blur'}
        ]
      }
    }
  },
  created() {
    this.getCaptcha();
  },
  methods:{
    handleSubmit (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          // console.log('发送axios注册请求')

          //将请求参数封装在json对象里
          let params = new URLSearchParams();
          params.append('nickname', this.formCustom.nickName);
          params.append('password', this.formCustom.passwd);
          params.append('uuid', this.uuid);
          params.append('phone', this.phone);
          params.append('captcha', this.verificationCode);
          params.append('gender', this.gender);

          this.$http.post('/api/register',params).then(res=>{
            let code = res.data.code   //获取响应状态吗
            switch(code){
              case 200://注册成功跳转至登录页面
                this.$Message.success('注册成功,正在跳转登录页面');
                this.$router.replace('/Login')
                break
              default:    //失败
                this.$Message.error('注册失败：'+res.data.codeInfo);
            }
          }).catch(error=>{
            console.log(error)
          })
        } else {
          this.$Message.error('您的输入异常，请重新填写！');
        }
      })
    },
    //qrBase64是后台传回来的base64数据
    handleDownloadQrIMg(qrBase64) {
      // 这里是获取到的图片base64编码,这里只是个例子哈，要自行编码图片替换这里才能测试看到效果
      const imgUrl = `data:image/png;base64,${qrBase64}`
      // 如果浏览器支持msSaveOrOpenBlob方法（也就是使用IE浏览器的时候），那么调用该方法去下载图片
      if (window.navigator.msSaveOrOpenBlob) {
        const bstr = atob(imgUrl.split(',')[1])
        let n = bstr.length
        const u8arr = new Uint8Array(n)
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n)
        }
        const blob = new Blob([u8arr])
        window.navigator.msSaveOrOpenBlob(blob, 'chart-download' + '.' + 'png')
      } else {
        // 这里就按照chrome等新版浏览器来处理
        const a = document.createElement('a')
        a.href = imgUrl
        a.setAttribute('download', 'chart-download')
        a.click()
      }
    },
    //向服务器请求验证码
    getCaptcha(){
      this.$http.get('/api/getCaptcha').then(res=>{
        let cod = res.data.data.VerifyBase64
        this.uuid = res.data.data.uuid
        this.img_url ='data:image/png;base64,'+cod
        // console.log('code',cod)
        // console.log('img_url:',this.img_url)
      }).catch(error=>{
        console.log(error)
      })
    }
  }
}
</script>

<style scoped>
#register {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
  background-image: url("../assets/images/register-background.jpeg");
  background-size: cover;
  position: fixed;
}

.register-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
}
.register-code {
  width: 38%;
  height: 37px;
  float: right;
}
.register-code-img{
  cursor: pointer;
  vertical-align: middle;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}
.register-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
</style>
